package com.thoughtsFromThePot;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Vector;


import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;
import android.widget.Toast;

/**************************************
 Things to do:
 
 IDEA
 ------
 Topic/idea/inspiration of the day/week to spark thoughts?
 or
 featured thought of the week (pick a good one, or the one with best ratings)?
 
 FOR V1:
 Complete code to handle orientation changes
 DONE -- Scrolling fade on top and bottom should be themed color
 DONE -- Toilet should be "images coming soon"
 Get More Thoughts button slides to right when posts not long enough
 
 Theme settings menu
 Theme posting menu
 Add more settings:
 	Complete themeing
 	Number of thoughts to display
 	Default username

**************************************/

public class ThoughtsFromThePot extends Activity{
	/* Global Constants*/
	private int thoughtId;
	
	/********* FLAGS ********************/
	private boolean stallSpinnerActivated = false;
	
	/********* DIALOG CONSTANTS *********/
	private static final int DIALOG_RATING_ID = 0;
	private static final int DIALOG_OTHER_ID = 1;
	private Dialog dialog;
	
	public static final String DATE_FORMAT_NOW = "E, dd MMM yyyy HH:mm:ss";
	boolean FEEDSUCCESS = false;
	private Handler handler = new Handler();
	public static refreshFeed runnable;
    public static Thread thread;
    private String username = "hey";
    private int state;
    
    /********* REFRESH TYPE CONSTANTS *********/
    /*display new thoughts or top thoughts*/
    private final int REFRESH_TYPE_NEW = 0;
    private final int REFRESH_TYPE_TOP = 1;
    private final int REFRESH_TYPE_POST = 2;
    private final int REFRESH_TYPE_STALL = 3;
    /*append or refresh completely*/
    private final int REFRESH_TYPE_APPEND = 1;
    private final int REFRESH_TYPE_ERASE = 0;
    
    private final int POST_THOUGHT = 0;
    private final int SETTINGS = 1;
    
    private int displayThoughtType = 0;
    private int thoughtPage = REFRESH_TYPE_NEW;
	
    private ArrayList<thoughtContainer> thoughtList = null;
    private ArrayList<String> savedStalls = new ArrayList<String>(); 
    private ArrayList<String> savedStallsPasswords = new ArrayList<String>(); 
    
    /********* SETTINGS MENU *****************/
    private String themeLightColor = "#4ab529";
    private String themeDarkColor = "#309412";
    private String thoughtColor1 = "#272727";
    private String thoughtColor2 = "#000000";
    private String thoughtColor3 = "#3c3c3c";
    private String textColor1 = "#ffffff";
    private String textColor2 = "#ffffff";
    private String pageDecorColor = "1";
    private int themeNumber = 0;  
    private String defaultNumThoughts = "25";
    private String defaultNumThoughtsToAdd = "15";
    private Boolean hapticEnabled = true;
    
	private final String OUTPUT_DIRECTORY = Environment.getExternalStorageDirectory() + "/Android/data/com.thoughtsFromThePot/";
	private final String SETTINGS_FILE = "settings.dat";
	
	/********** SESSION INFORMATION ***********/
	private String currentStallName = "Global";
	private String currentStallPassword = "";
	
	///private boolean lockButton = false; //Controls buttons when loading thoughts
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        getPrefs();
  
        //GET thoughtList from the bundle if it is not null
        if (savedInstanceState != null) {
        	thoughtList = savedInstanceState.getParcelableArrayList("thoughtList");
        	displayThoughtType = savedInstanceState.getInt("pageNumber");
        }
        
        //Toast.makeText(getApplicationContext(), "Recreating app... ",Toast.LENGTH_SHORT).show();
        
        //loadSettings();
        loadThoughtScreen();
    }
    
//    private void loadSettings() {
//    	// Read settings
//    	String data[] = readSettings(this).split(",");
//    	if (data.length > 2) {
//	    	themeLightColor = data[0];
//	    	themeDarkColor = data[1];
//	    	themeNumber = Integer.parseInt(data[2]);
//    	}
//    }
//    
//    private String readSettings(Context context) 
//    { 
//    	String returnData = "";
//    	ObjectInputStream  objectIn = null; 
//    	try { 
//    		File file = new File(OUTPUT_DIRECTORY); 
//    		if(file.exists()) { 
//    			file = new File(OUTPUT_DIRECTORY + SETTINGS_FILE); 
//    			if(file.exists()) {
//    				FileInputStream stream = new FileInputStream(OUTPUT_DIRECTORY + SETTINGS_FILE); 
//    				objectIn = new ObjectInputStream(new BufferedInputStream(stream)); 
//    				
//    				returnData = objectIn.readLine();
//    				returnData = returnData.substring(2, returnData.length());
//    				
//    				Toast.makeText(context, "Settings read! ",Toast.LENGTH_SHORT).show();
//    			}
//    		}   
//    		return returnData; 
//    	} catch(IOException e) { 
//    		Toast.makeText(context, "Failed to read settings.",Toast.LENGTH_SHORT).show();
//    		e.printStackTrace(); 
//    		return ""; 
//    	} finally { 
//    		try { 
//    			if(objectIn != null) 
//    				objectIn.close(); 
//    		} 
//    		catch(IOException ex) { 
//    			ex.printStackTrace(); 
//    		} 
//    	} 
//    } 
    
    /* Loads the main screen which displays thoughts */
    public void loadThoughtScreen() {
    	setContentView(R.layout.thoughtfeed);
    	
    	//table background thoughtColor2
    	//app background textColor1
    	ScrollView thoughtScroll = (ScrollView) findViewById(R.id.thoughtScrollView);
    	thoughtScroll.setBackgroundColor(Color.parseColor(thoughtColor2));
    	
    	TextView title = (TextView) findViewById(R.id.currentStall);
        title.setText(currentStallName + ": ");
    	
//    	LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
//    	mainLayout.setBackgroundColor(Color.parseColor(textColor1));
//    	
//    	//Set top row background to light color
//    	TableRow tr = (TableRow) findViewById(R.id.tableRow1);
//    	tr.setBackgroundColor(Color.parseColor(themeLightColor));
//
//    	//Set top row accent background to dark color
//    	TableRow tr2 = (TableRow) findViewById(R.id.tableRow2);
//    	tr2.setBackgroundColor(Color.parseColor(themeDarkColor));
    	
//    	TableRow tr3 = (TableRow) findViewById(R.id.TableRow01);
//    	tr3.setBackgroundColor(Color.parseColor(thoughtColor2));
//    	
//    	if (pageDecorColor.equals("0")) {
//    		ImageView leftDots = (ImageView) findViewById(R.id.leftDots);
//    		leftDots.setImageResource(R.drawable.leftdotsblack);
//    		ImageView rightDots = (ImageView) findViewById(R.id.rightDots);
//    		rightDots.setImageResource(R.drawable.rightdotsbigblack);
//    	} else if (pageDecorColor.equals("1")) {
//    		ImageView leftDots = (ImageView) findViewById(R.id.leftDots);
//    		leftDots.setImageResource(R.drawable.leftdotswhite);
//    		ImageView rightDots = (ImageView) findViewById(R.id.rightDots);
//    		rightDots.setImageResource(R.drawable.rightdotsbigwhite);
//    	}
    	
    	//Required to text wrap the thought column
        TableLayout thoughtTable = (TableLayout) findViewById(R.id.thoughtTable);
        thoughtTable.setColumnShrinkable(0, true); 

        //Display loading
        addRow(thoughtTable, Color.parseColor(thoughtColor2), getTime(), "Connecting to the ThoughtsFromThePot server...", "",0 , 0, 0, 0, true);
        
        Button thoughtButton = (Button) findViewById(R.id.thoughtButton);
        thoughtButton.setOnClickListener(thoughtButtonListener);
        if (hapticEnabled) {
        	thoughtButton.setHapticFeedbackEnabled(true);
        	thoughtButton.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
        
        Button stallButton = (Button) findViewById(R.id.stallButton);
        stallButton.setOnClickListener(stallButtonListener);
        if (hapticEnabled) {
        	stallButton.setHapticFeedbackEnabled(true);
        	stallButton.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
        
        Button postButton = (Button) findViewById(R.id.postButton);
        postButton.setOnClickListener(writeButtonListener);
        if (hapticEnabled) {
        	postButton.setHapticFeedbackEnabled(true);
        	postButton.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
        
        Button settingsButton = (Button) findViewById(R.id.settingsButton);
        settingsButton.setOnClickListener(settingsButtonListener);
        if (hapticEnabled) {
        	settingsButton.setHapticFeedbackEnabled(true);
        	settingsButton.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
              
        if (thoughtList == null || thoughtList.isEmpty()) {
        	runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_NEW, currentStallName, currentStallPassword, "");
            thread = new Thread(runnable);    
            thread.start();  
            //lockButton = false;
        } else {
        	rethemeFeedscreen();
        }     
    }
    
    /* Adds a row to the thought feed */
    public void addRow(TableLayout table, int color, String shitterStr, String thoughtStr, String thoughtTime, int sideColor, int id, int thoughtLikes, int thoughtDislikes, Boolean errorMsg) {
    	
    	/* Create a new row to be added. */
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(
                       LayoutParams.FILL_PARENT,
                       LayoutParams.WRAP_CONTENT));
        tr.setBackgroundColor(color);


        //Linear Layout to create 1 table column
        LinearLayout linearWrapper = new LinearLayout(this);
        linearWrapper.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        
        //Row
    	//RelativeLayout Container
        RelativeLayout imageLayout1 = new RelativeLayout(this);
        imageLayout1.setBackgroundColor(Color.TRANSPARENT);
        //imageLayout.setPadding(3,3,3,3);
        imageLayout1.setLayoutParams(new LayoutParams(
        		10,
                LayoutParams.FILL_PARENT));
        imageLayout1.setGravity(Gravity.LEFT);
    	//FrameLayout Container
    	FrameLayout imageBorder1 = new FrameLayout(this);
    	imageBorder1.setLayoutParams(new LayoutParams(
                5,
                LayoutParams.FILL_PARENT));
        	//Image for user icon
        	ImageView userIcon1 = new ImageView(this);
        	if (sideColor == 1) {
        		userIcon1.setBackgroundColor(Color.parseColor("#26b226"));
        	} else
        		userIcon1.setBackgroundColor(Color.parseColor("#000000"));
        	userIcon1.setImageResource(R.drawable.trans1x1);
        	//userIcon.setMaxWidth(32);
        	//userIcon.setMaxHeight(32);
        	userIcon1.setAdjustViewBounds(true);
        	userIcon1.setLayoutParams(new LayoutParams(
                10,
                LayoutParams.FILL_PARENT));
        	userIcon1.setPadding(0,0,0,0);
          
        //Set border for the user icon
        //imageBorder.setBackgroundColor(Color.parseColor(textColor1));
        //imageBorder.setPadding(1, 1, 1, 1);
        imageBorder1.addView(userIcon1);
	    //Add image to container, add container to table row
	    imageLayout1.addView(imageBorder1);
        linearWrapper.addView(imageLayout1);
        
       
        //TableLayout Container
        TableLayout thoughtLayout = new TableLayout(this);
        thoughtLayout.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        thoughtLayout.setGravity(Gravity.LEFT);
        
        /*Username*/
        // Create a TextView for the user's login name
        TextView shitter = new TextView(this);
        shitter.setText(shitterStr);
        shitter.setTextColor(Color.parseColor(themeLightColor));
        shitter.setTextSize(12);
        shitter.setTypeface(Typeface.DEFAULT_BOLD);
        shitter.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        shitter.setGravity(Gravity.LEFT);
        shitter.setPadding(0, 2, 0, 0);
        thoughtLayout.addView(shitter);

        /*Thought*/
        //Create a TextView for the user's thought
        TextView thought = new TextView(this);
        thought.setText(thoughtStr);
        thought.setTextColor(Color.parseColor(textColor1));
        thought.setTextSize(12);
        thought.setGravity(Gravity.BOTTOM);
        thought.setEllipsize(null);
        thought.setSingleLine(false);
        thought.setHorizontallyScrolling(false);
        thought.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        thought.setGravity(Gravity.LEFT);
        thoughtLayout.addView(thought);
        
        /*Time*/
        LinearLayout timeLayout = new LinearLayout(this);
        timeLayout.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        //Create a TextView for the time of the user's thought
        TextView time = new TextView(this);
        time.setText(thoughtTime);
        time.setTextColor(Color.parseColor(textColor2));
        time.setTextSize(10);
        time.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
        time.setGravity(Gravity.BOTTOM);
        time.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, 1f));
        time.setPadding(0, 0, 0, 4);
        time.setGravity(Gravity.LEFT);
        timeLayout.addView(time);
        
        if (errorMsg == false) {
			tr.setId(id);
			tr.setClickable(true);
			tr.setOnClickListener(thoughtRowListener);
			
			TextView rating = new TextView(this);
	        rating.setText("Likes: " + thoughtLikes + "  Dislikes: " + thoughtDislikes + "  ");
	        rating.setTextColor(Color.parseColor(textColor2));
	        rating.setTextSize(10);
	        rating.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
	        rating.setGravity(Gravity.BOTTOM);
	        rating.setLayoutParams(new LayoutParams(
	                LayoutParams.WRAP_CONTENT,
	                LayoutParams.WRAP_CONTENT, 1f));
	        rating.setPadding(0, 0, 0, 4);
	        rating.setGravity(Gravity.RIGHT);
	        
	        timeLayout.addView(rating);
        }
  
        thoughtLayout.addView(timeLayout);
	    
        //Add new layout to the table row
        linearWrapper.addView(thoughtLayout);
      
        if (sideColor == 2) {
	        //Row
	    	//RelativeLayout Container
	        RelativeLayout imageLayout = new RelativeLayout(this);
	        imageLayout.setBackgroundColor(Color.TRANSPARENT);
	        //imageLayout.setPadding(3,3,3,3);
	        imageLayout.setLayoutParams(new LayoutParams(
	        		50,
	                LayoutParams.FILL_PARENT, 1f));
	        imageLayout.setGravity(Gravity.RIGHT);
	    	//FrameLayout Container
	    	FrameLayout imageBorder = new FrameLayout(this);
	    	imageBorder.setLayoutParams(new LayoutParams(
	                15,
	                LayoutParams.FILL_PARENT));
	        	//Image for user icon
	        	ImageView userIcon = new ImageView(this);
	        	userIcon.setBackgroundColor(Color.parseColor("#26b226"));
	        	userIcon.setImageResource(R.drawable.trans1x1);
	        	//userIcon.setMaxWidth(32);
	        	//userIcon.setMaxHeight(32);
	        	userIcon.setAdjustViewBounds(true);
	        	userIcon.setLayoutParams(new LayoutParams(
	                15,
	                LayoutParams.FILL_PARENT));
	        	userIcon.setPadding(0,0,0,0);
	          
	        //Set border for the user icon
	        //imageBorder.setBackgroundColor(Color.parseColor(textColor1));
	        //imageBorder.setPadding(1, 1, 1, 1);
	        imageBorder.addView(userIcon);
		    //Add image to container, add container to table row
		    imageLayout.addView(imageBorder);
	        linearWrapper.addView(imageLayout);
        }
        
        
        tr.addView(linearWrapper);
	        
//	    //For athestics, add a 1px border (tableRow used for this effect) between rows
//	    TableRow rowSpacer = new TableRow(this);
//	    rowSpacer.setLayoutParams(new LayoutParams(
//                       LayoutParams.FILL_PARENT,
//                       LayoutParams.WRAP_CONTENT));
//	    rowSpacer.setBackgroundColor(Color.parseColor(thoughtColor3));
//	    rowSpacer.setPadding(0, 1, 0, 0);
		    
	    //Add new completed row to the "thought feed" 
	    table.addView(tr,new TableLayout.LayoutParams(
	             LayoutParams.FILL_PARENT,
	             LayoutParams.WRAP_CONTENT));
//	    table.addView(rowSpacer,new TableLayout.LayoutParams(
//	             LayoutParams.FILL_PARENT,
//	             LayoutParams.WRAP_CONTENT));
    }
    
    private void displayPostPage () {
    	TableLayout table = (TableLayout) findViewById(R.id.thoughtTable);
    	
    	/* Create a new row to be added. */
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(
                       LayoutParams.FILL_PARENT,
                       LayoutParams.WRAP_CONTENT));
        tr.setBackgroundColor(Color.parseColor(thoughtColor1));

        //Linear Layout to create 1 table column
        LinearLayout linearWrapper = new LinearLayout(this);
        linearWrapper.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT, 1f));
        
        TableLayout postTable = new TableLayout(this);
        postTable.setBackgroundColor(Color.parseColor("#000000"));
        postTable.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT, 1f));
        
        TextView userText = new TextView(this);
        userText.setText(" Username:");
        userText.setTextColor(Color.parseColor("#ffffff"));
        userText.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        userText.setPadding(0, 8, 0, 0);
        //tr1.addView(userText);
        postTable.addView(userText);
        
        EditText userEntry = new EditText(this);
        userEntry.setText("");
        userEntry.setId(1099);
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(50);
        userEntry.setFilters(FilterArray);
        userEntry.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        //postTable.addView(tr1);
        postTable.addView(userEntry);
       
        TextView thoughtText = new TextView(this);
        thoughtText.setText(" Thought:");
        thoughtText.setTextColor(Color.parseColor("#ffffff"));
        thoughtText.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        //tr2.addView(thoughtText);
        postTable.addView(thoughtText);
        
        EditText thoughtEntry = new EditText(this);
        thoughtEntry.setText("");
        thoughtEntry.setId(1100);
        FilterArray[0] = new InputFilter.LengthFilter(200);
        userEntry.setFilters(FilterArray);
        thoughtEntry.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        //postTable.addView(tr2);
        postTable.addView(thoughtEntry);
        
        LinearLayout postLayout = new LinearLayout(this);
        
        Button postButton = new Button(this);
        postButton.setText("Post Thought");
        postButton.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT,1f));
        //postButton.setGravity(Gravity.RIGHT);
        postButton.setOnClickListener(postThoughtListener);
        
        //postLayout.setPadding(0, 6, 0, 0);
        postLayout.addView(postButton);
        postLayout.setGravity(Gravity.RIGHT);
        
        postTable.addView(postLayout);
   
        linearWrapper.addView(postTable);
        //linearWrapper.addView(postLayout);
        
    	tr.addView(linearWrapper);
    	
    	table.addView(tr,new TableLayout.LayoutParams(
	             LayoutParams.FILL_PARENT,
	             LayoutParams.WRAP_CONTENT));
    }
    
	private void displayStallPage () {
    	TableLayout table = (TableLayout) findViewById(R.id.thoughtTable);
    	
    	/* Create a new row to be added. */
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(
                       LayoutParams.FILL_PARENT,
                       LayoutParams.WRAP_CONTENT));
        tr.setBackgroundColor(Color.parseColor(thoughtColor1));

        //Linear Layout to create 1 table column
        LinearLayout linearWrapper = new LinearLayout(this);
        linearWrapper.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT, 1f));
        
        TableLayout stallTable = new TableLayout(this);
        stallTable.setBackgroundColor(Color.parseColor("#000000"));
        stallTable.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT, 1f));
        
        TextView changeStallText = new TextView(this);
        changeStallText.setText(" Change Current Stall:");
        changeStallText.setTextColor(Color.parseColor("#ffffff"));
        changeStallText.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        changeStallText.setPadding(0, 8, 0, 0);
        //tr1.addView(userText);
        stallTable.addView(changeStallText);
        
        Spinner savedStallChanger = new Spinner(this);
		ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this, R.layout.centeredspinner,
                    savedStalls);
		savedStallChanger.setOnItemSelectedListener(stallSpinnerListener);
		
		spinnerArrayAdapter.setDropDownViewResource(R.layout.centeredspinner);
        savedStallChanger.setAdapter(spinnerArrayAdapter);
        savedStallChanger.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT, 1f));
        //postTable.addView(tr1);
        stallTable.addView(savedStallChanger);
       
        LinearLayout stallLayout = new LinearLayout(this);
        
        Button createStallButton = new Button(this);
        createStallButton.setText("Create Stall");
        createStallButton.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT,1f));
        //createStallButton.setGravity(Gravity.RIGHT);
        createStallButton.setOnClickListener(createStallListener);
        
        Button joinStallButton = new Button(this);
        joinStallButton.setText("Join Stall");
        joinStallButton.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT,1f));
        //joinStallButton.setGravity(Gravity.RIGHT);
        joinStallButton.setOnClickListener(joinStallListener);
        
        stallLayout.setPadding(0, 6, 0, 0);
        //stallLayout.addView(createStallButton);
        //stallLayout.addView(joinStallButton);
        stallLayout.setGravity(Gravity.RIGHT);
        
        stallTable.addView(createStallButton);
        stallTable.addView(joinStallButton);
        //stallTable.addView(stallLayout);
   
        linearWrapper.addView(stallTable);
        //linearWrapper.addView(postLayout);
        
    	tr.addView(linearWrapper);
    	
    	table.addView(tr,new TableLayout.LayoutParams(
	             LayoutParams.FILL_PARENT,
	             LayoutParams.WRAP_CONTENT));
    }
    
    // Clears the table feed of all thought posts
    public void removeAllFeedRows () {
    	TableLayout table = (TableLayout) findViewById(R.id.thoughtTable);
    	
    	while (table.getChildCount() > 0) {
    		table.removeViewAt(0);
    	}
    }
    
    private void addMoreButton(int color) {
    	TableRow tr = new TableRow(this);
    	LinearLayout ll = new LinearLayout(this);
    	Button moreButton = new Button(this);
    	
    	moreButton.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    	
    	moreButton.setGravity(Gravity.CENTER);
                
    	ll.setPadding(0,0,0,0);

    	TableLayout table = (TableLayout) findViewById(R.id.thoughtTable);
    	
    	moreButton.setText("Get More Thoughts");
    	moreButton.setOnClickListener(moreButtonListener);
    	moreButton.setBackgroundColor(Color.parseColor(themeLightColor));
    	moreButton.setTextColor(Color.WHITE);
    	moreButton.setTypeface(Typeface.DEFAULT_BOLD);
    	
    	ll.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    	ll.addView(moreButton);
    	//ll.setBackgroundColor(Color.parseColor(themeLightColor));
    	ll.setGravity(Gravity.CENTER);
    	
    	tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    	tr.setBackgroundColor(Color.parseColor(themeDarkColor));
    	tr.addView(ll);
    	tr.setGravity(Gravity.CENTER);
		    
	    //Add new completed row to the "thought feed" 
	    table.addView(tr,new TableLayout.LayoutParams(
	             LayoutParams.FILL_PARENT,
	             LayoutParams.WRAP_CONTENT));
    }
	
    /***** Subclass of ThoughtsFromThePot *****/
    // Used to refresh the thought feed as a new thread
	public class refreshFeed implements Runnable {
		private int refreshType = 0;
		private int totalRefresh = 0;
		private String stallpassword = "";
		private String stallname = ""; 
		private String excep = null;
		private String storage = "";
		
		public refreshFeed(int type, int refresh, String name, String password, String storage) {
			refreshType = type;
			totalRefresh = refresh;
			stallpassword = password;
			stallname = name;
			this.storage = storage;
		}
		
        public void run() 
        {
        	servletConnector sc = new servletConnector();
        	
        	//Set background color to the first color
        	//LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
        	//mainLayout.setBackgroundColor(Color.parseColor(thoughtColor1));
        	
        	//lockButton = true;
        	try {
	        	if (totalRefresh == REFRESH_TYPE_ERASE) {
	        		if (refreshType == REFRESH_TYPE_NEW) {
	                	thoughtList = sc.getThoughts(defaultNumThoughts, stallname, stallpassword);
	                	handler.sendEmptyMessage(0);
	            	} else if (refreshType == REFRESH_TYPE_TOP) {
	            		thoughtList = sc.getTopThoughts(defaultNumThoughts, stallname, stallpassword);
	                	handler.sendEmptyMessage(0);
	            	}	 
	        	} else if (totalRefresh == REFRESH_TYPE_APPEND) {
	        		if (refreshType == REFRESH_TYPE_NEW) {
	        			thoughtList.addAll(sc.getThoughts(defaultNumThoughtsToAdd, thoughtList.get(thoughtList.size()-1).getId(), stallname, stallpassword));
	                	handler.sendEmptyMessage(0);
	            	} else if (refreshType == REFRESH_TYPE_TOP) {
	            		//thoughtList.addAll(sc.getTopThoughts(defaultNumThoughtsToAdd, thoughtList.get(thoughtList.size()-1).getId(), stallname, stallpassword));
	                	//handler.sendEmptyMessage(0);
	            	}
	        	}
        	} catch (TFTPException e) {
        		//toastDisplay(e.getMessage());
        		excep = e.getMessage();
        		handler.sendEmptyMessage(0);
//        		if (joiningStall) {
//        			createJoinStallDialog("Invalid stall name or password. Please try again.");
//        		} else {
//        			//call password dialog (session expired, please enter PW)
//        			createStallPasswordDialog("Session Expired. Please re-enter password for stall: " + stallname);
//        		}
        		//throw TFTPAuthenticationException;
        	}
        	
        	//lockButton = false;
        	  
            handler.post(new Runnable() 
            {
                public void run() {
                	if (refreshType == displayThoughtType && excep == null) {
                		//Need to saved pass/stall
                		//savedStallsPasswords
                		if (storage.equals("join")) {
	                		savedStalls.add(stallname);
	                		savedStallsPasswords.add(stallpassword);
	                		
	                		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());//getPreferences(Activity.MODE_PRIVATE);
	            			SharedPreferences.Editor editor = preferences.edit();
	            			editor.putString("savedStalls", savedStalls.toString().substring(1, savedStalls.toString().length()-1));
	            			editor.putString("savedStallsPasswords", savedStallsPasswords.toString());
	            			editor.commit();
                		}
                		
	                	TableLayout thoughtTable = (TableLayout) findViewById(R.id.thoughtTable);
	                	removeAllFeedRows();
	                	
	                	displayThoughtType = REFRESH_TYPE_NEW;
		        		setButtonBottom(1);
		        		TextView title1 = (TextView) findViewById(R.id.pageTitle);
		        		title1.setText("new thoughts");
	                	currentStallName = stallname;
	                	currentStallPassword = stallpassword;
	                	
	                	TextView title = (TextView) findViewById(R.id.currentStall);
	                    title.setText(currentStallName + ": ");
	                	
	                	if (thoughtList.size() > 0) {
	        	        	try {
	        	        		//Add all thoughts gathered to the table feed
	        		        	int forLength = thoughtList.size();
	        		        	//while(arrayCounter > 0)
	        		        	for (int i = 0; i < forLength; i++)
	        		            {
	        		            	//arrayCounter--;
	        		            	thoughtContainer tc = thoughtList.get(i);
	        		            	
	        		            	if (i % 2 == 1) {
	        		            		addRow(thoughtTable, Color.parseColor(thoughtColor1), tc.getUsername(), tc.getThought(), tc.getDate(), 1, i, tc.getLikes(), tc.getDislikes(), false);
	        		                } else {
	        		                	addRow(thoughtTable, Color.parseColor(thoughtColor2), tc.getUsername(), tc.getThought(), tc.getDate(), 0, i, tc.getLikes(), tc.getDislikes(), false);
	        		                }
	        		            }
	        		        	
	        		        	if (displayThoughtType == 0) {
		        		        	//NOW ADD MORE BUTTON
		        		        	if ((forLength) % 2 == 1) {
		    		            		addMoreButton(Color.parseColor(thoughtColor1));
		    		                } else {
		    		                	addMoreButton(Color.parseColor(thoughtColor2));
		    		                }
	        		        	}
	        	        	} catch (Exception e) {
	        	        	}
	                	}
	                	else {
	                		addRow(thoughtTable, Color.parseColor(thoughtColor2), getTime(), "Unable to connect to the ThoughtsFromThePot server for refresh type: " + refreshType + " and total refresh " + totalRefresh + ". Ensure you are connected to the internet and try again later.", "", 0, 0, 0, 0, true);
	                	}
	                } else {
	                	toastDisplay(excep);
	                }
                }
            });
        }    
    }
	
	private void toastDisplay(String toast) {
		Toast.makeText(getApplicationContext(), toast,Toast.LENGTH_SHORT).show();
	}
	
	private void rethemeFeedscreen() {
    	ScrollView thoughtScroll = (ScrollView) findViewById(R.id.thoughtScrollView);
    	thoughtScroll.setBackgroundColor(Color.parseColor(thoughtColor2));
    	
//    	LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
//    	mainLayout.setBackgroundColor(Color.parseColor(textColor1));
//    	
//		 //Set top row background to light color
//     	TableRow tr = (TableRow) findViewById(R.id.tableRow1);
//     	tr.setBackgroundColor(Color.parseColor(themeLightColor));
//
//     	//Set top row accent background to dark color
//     	TableRow tr2 = (TableRow) findViewById(R.id.tableRow2);
//     	tr2.setBackgroundColor(Color.parseColor(themeDarkColor));
//     	
//    	TableRow tr3 = (TableRow) findViewById(R.id.TableRow01);
//    	tr3.setBackgroundColor(Color.parseColor(thoughtColor2));
//    	
//    	if (pageDecorColor.equals("0")) {
//    		ImageView leftDots = (ImageView) findViewById(R.id.leftDots);
//    		leftDots.setImageResource(R.drawable.leftdotsblack);
//    		ImageView rightDots = (ImageView) findViewById(R.id.rightDots);
//    		rightDots.setImageResource(R.drawable.rightdotsbigblack);
//    	} else if (pageDecorColor.equals("1")) {
//    		ImageView leftDots = (ImageView) findViewById(R.id.leftDots);
//    		leftDots.setImageResource(R.drawable.leftdotswhite);
//    		ImageView rightDots = (ImageView) findViewById(R.id.rightDots);
//    		rightDots.setImageResource(R.drawable.rightdotsbigwhite);
//    	}
//    	
		handler.sendEmptyMessage(0);
		
		TableLayout thoughtTable = (TableLayout) findViewById(R.id.thoughtTable);
    	removeAllFeedRows();
    	
    	if (thoughtList.size() > 0) {
        	try {
        		//Add all thoughts gathered to the table feed
	        	int forLength = thoughtList.size();
	        	//while(arrayCounter > 0)
	        	for (int i = 0; i < forLength; i++)
	            {
	            	//arrayCounter--;
	            	thoughtContainer tc = thoughtList.get(i);
	            	
	            	if (i % 2 == 1) {
	            		addRow(thoughtTable, Color.parseColor(thoughtColor1), tc.getUsername(), tc.getThought(), tc.getDate(), 1, i, tc.getLikes(), tc.getDislikes(), false);
	                } else {
	                	addRow(thoughtTable, Color.parseColor(thoughtColor2), tc.getUsername(), tc.getThought(), tc.getDate(), 0, i, tc.getLikes(), tc.getDislikes(), false);
	                }
	            }
	        	
	        	if (displayThoughtType == 0) {
		        	//NOW ADD MORE BUTTON
		        	if ((forLength) % 2 == 1) {
	            		addMoreButton(Color.parseColor(thoughtColor1));
	                } else {
	                	addMoreButton(Color.parseColor(thoughtColor2));
	                }
	        	}
        	} catch (Exception e) {
        	}
    	}
    	else {
    		addRow(thoughtTable,Color.parseColor(thoughtColor2), getTime(), "Unable to connect to the ThoughtsFromThePot server. Ensure you are connected to the internet and try again later.", "", 0, 0, 0, 0, true);
    	}
	}
	
	boolean CheckboxPreference;
    String ListPreference;
    String editTextPreference;
    String ringtonePreference;
    String secondEditTextPreference;
    String customPref;

    private void getPrefs() {
            // Get the xml/preferences.xml preferences
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            hapticEnabled = prefs.getBoolean("hapticPref", true);
         
            //String[] themeArray = prefs.getString("themeColor", "#2b559b,#12346c,#eeeeee,#ffffff,#d9d9d9,#000000,#000000,0").split(",");
            //themeLightColor = themeArray[0];
            //themeDarkColor = themeArray[1];
            //thoughtColor1 = themeArray[2];
            //thoughtColor2 = themeArray[3];
            //thoughtColor3 = themeArray[4];
            //textColor1 = themeArray[5];
            //textColor2 = themeArray[6];
            //pageDecorColor = themeArray[7];
            String[] savedStallsArray = (String[]) prefs.getString("savedStalls", "Global").split(",");  
            savedStalls.clear();
            Collections.addAll(savedStalls, savedStallsArray); 
            
            String[] savedStallsPasswordsArray = (String[]) prefs.getString("savedStallsPasswords", "Global").split(",");  
            savedStallsPasswords.clear();
            Collections.addAll(savedStallsPasswords, savedStallsPasswordsArray); 

//          editTextPreference = prefs.getString("editTextPref", "Nothing has been entered");
//			ringtonePreference = prefs.getString("ringtonePref", "DEFAULT_RINGTONE_URI");
//			secondEditTextPreference = prefs.getString("SecondEditTextPref", "Nothing has been entered");
            
//          // Get the custom preference
//          SharedPreferences mySharedPreferences = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
//          customPref = mySharedPreferences.getString("myCusomPref", "");
    }
    
    private void setButtonBottom(int number) {
    	
    	Button buttonBottom = (Button) findViewById(R.id.thoughtButton);
    	buttonBottom.setBackgroundResource(R.drawable.newbuttongreen);
    	
    	buttonBottom = (Button) findViewById(R.id.thoughtButton);
    	buttonBottom.setBackgroundResource(R.drawable.topbuttongreen);
    	
    	buttonBottom = (Button) findViewById(R.id.stallButton);
    	buttonBottom.setBackgroundResource(R.drawable.stallbuttongreen);
    	
    	buttonBottom = (Button) findViewById(R.id.postButton);
    	buttonBottom.setBackgroundResource(R.drawable.writebuttongreen);
    	
    	buttonBottom = (Button) findViewById(R.id.settingsButton);
    	buttonBottom.setBackgroundResource(R.drawable.settingsbuttongreen);
    		
    	if (number == 0) {
    		buttonBottom = (Button) findViewById(R.id.thoughtButton);
    		buttonBottom.setBackgroundResource(R.drawable.newbuttonwhite);
    	} else if (number == 1) {
    		buttonBottom = (Button) findViewById(R.id.thoughtButton);
    		buttonBottom.setBackgroundResource(R.drawable.topbuttonwhite);
    	} else if (number == 2) {
    		buttonBottom = (Button) findViewById(R.id.stallButton);
    		buttonBottom.setBackgroundResource(R.drawable.stallbuttonwhite);
    	} else if (number == 3) {
    		buttonBottom = (Button) findViewById(R.id.postButton);
    		buttonBottom.setBackgroundResource(R.drawable.writebuttonwhite);
    	} else if (number == 4) {
    		buttonBottom = (Button) findViewById(R.id.settingsButton);
    		buttonBottom.setBackgroundResource(R.drawable.settingsbuttonwhite);
    	}
    	
    }
	
	/********************************************
	 *  ANDROID LIFECYCLE FUNCTIONS TO OVERRIDE 
	 ********************************************/
	
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
        getPrefs();
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
    
    /* This is called whenever a configuration change causes the app to restart */
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
      savedInstanceState.putString("Username", username);
      savedInstanceState.putParcelableArrayList("thoughtList", thoughtList);
      savedInstanceState.putInt("pageNumber", displayThoughtType);
      savedInstanceState.putStringArrayList("savedStalls", savedStalls);
      savedInstanceState.putStringArrayList("savedStallsPasswords", savedStallsPasswords);
      super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      // Restore UI state from the savedInstanceState.
      // This bundle has also been passed to onCreate.
      // username = savedInstanceState.getString("Username");
    }
    
    /* This function is called whenever a spawned activity returns a result and 
       by using the requestCode, we can determine which activity call was made  */
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
         switch(requestCode)
         {
             case POST_THOUGHT:
	             if (resultCode == RESULT_OK) {
	            	//loadThoughtScreen();
	            	//Toast.makeText(getApplicationContext(), "Refreshing thoughts... ",Toast.LENGTH_SHORT).show();
	            	runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_NEW, currentStallName, currentStallPassword, "");
	                thread = new Thread(runnable);    
	                thread.start();
	                //lockButton = false;
	             }
             break;
             
             case SETTINGS:
            	 getPrefs();
            	 if (displayThoughtType == REFRESH_TYPE_POST) {
                 	removeAllFeedRows();
                 	displayPostPage();
                 } else {        
                	rethemeFeedscreen();
                 }
             break;
         } // end switch
    }
    
    /**************************************
               BUTTON LISTENERS
    *************************************/
    
    private OnClickListener postThoughtListener = new OnClickListener() {
        public void onClick(View v) {
        	if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}
        	
        	TextView usernameText = (TextView) findViewById(1099);
        	TextView thoughtText = (TextView) findViewById(1100);
        	CharSequence usernameChar = usernameText.getText();
        	CharSequence thoughtChar = thoughtText.getText();
        	
        	String thisUsername = usernameChar.toString();
        	String thisThought = thoughtChar.toString();
        	String result = null; 
        	
        	String testUsername = thisUsername.replaceAll(" ", "");
        	String testThought = thisThought.replaceAll(" ", "");
        	//TODO: ADD LOGIC - REMOVE ALL SPACES TEMPORARILY, IF NO TEXT EXISTS, DON'T POST
        	
        	if (testUsername == null || testThought == null || testUsername.length() == 0 || testThought.length() == 0) {
        		
        	} else {
	        	
	        	servletConnector sc = new servletConnector();
	        	
	        	try {
					result = sc.sendThought(thisThought, thisUsername, currentStallName, currentStallPassword);
				} catch (TFTPException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    		if (result.equals("1")) { //otherwise there was an error!
	    			Toast.makeText(getApplicationContext(), "Post succeeded. Refreshing thoughts...",Toast.LENGTH_SHORT).show();
	    			//SaveDataToFile("Thought: " + thisThought + ", Username: " + thisUsername + ", Date: " + getTime() + ", Result: " + result);
	
	    			displayThoughtType = REFRESH_TYPE_NEW;
	    			setButtonBottom(3);
	    	        	
	    	        TextView title = (TextView) findViewById(R.id.pageTitle);
	    	        title.setText("new thoughts");
	    			
	    			runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_ERASE, currentStallName, currentStallPassword, "");
		            thread = new Thread(runnable);    
		            thread.start(); 
		            //lockButton = false;
	    		}
	    		else {
	    			Toast.makeText(getApplicationContext(), "Post failed.",Toast.LENGTH_SHORT).show();
	    			//SaveDataToFile("Thought: " + thisThought + ", Username: " + thisUsername + ", Date: " + getTime() + ", Result: " + result);
	    		}
        	}
        }
    };
    
    private OnClickListener thoughtButtonListener = new OnClickListener() {
        public void onClick(View v) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
	        	}
	        	
	        	TextView title = (TextView) findViewById(R.id.pageTitle);
	        	
	        	if (thoughtPage == REFRESH_TYPE_NEW) {
	        		thoughtPage = REFRESH_TYPE_TOP;
	        		displayThoughtType = REFRESH_TYPE_TOP;
	        		setButtonBottom(0);
	        		title.setText("top thoughts");
	        		Toast.makeText(getApplicationContext(), "Loading new thoughts...",Toast.LENGTH_SHORT).show();
	        	} else if (thoughtPage == REFRESH_TYPE_TOP) {
	        		thoughtPage = REFRESH_TYPE_NEW;
	        		displayThoughtType = REFRESH_TYPE_NEW;
	        		setButtonBottom(1);
	        		title.setText("new thoughts");
	        		Toast.makeText(getApplicationContext(), "Loading top thoughts...",Toast.LENGTH_SHORT).show();
	        	} else {
	        		
	        	}
	        	
	        	runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_ERASE, currentStallName, currentStallPassword, "");
	            thread = new Thread(runnable);    
	            thread.start(); 
        }
    };
    
    private OnClickListener stallButtonListener = new OnClickListener() {
        public void onClick(View v) {
        	//if (lockButton == false) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
	        	}
	        	displayThoughtType = REFRESH_TYPE_STALL;

	        	setButtonBottom(2);
	        	
	        	TextView title = (TextView) findViewById(R.id.pageTitle);
	        	title.setText("stall options");
	        	
	        	removeAllFeedRows();
	        	displayStallPage();
        }
    };
    
    private OnClickListener createStallListener = new OnClickListener() {
        public void onClick(View v) {
        	//if (lockButton == false) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
	        	}

				//open a popup box for like vs dislike
				dialog = new Dialog(ThoughtsFromThePot.this);

				dialog.setContentView(R.layout.createstalldialog);
				dialog.getWindow();
				
				android.view.WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); 
                params.width = LayoutParams.FILL_PARENT; 
                params.height = LayoutParams.WRAP_CONTENT;
                dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); 
				
				dialog.setTitle("Create Stall");

				Button stallSubmitButton = (Button) dialog.findViewById(R.id.createStallSubmitButton);
				stallSubmitButton.setOnClickListener(createStallSubmitListener);
				
				Button stallCancelButton = (Button) dialog.findViewById(R.id.createStallCancelButton);
				stallCancelButton.setOnClickListener(createStallCancelListener);

				dialog.show();
        }
    };
    
    private OnClickListener joinStallListener = new OnClickListener() {
        public void onClick(View v) {
        	//if (lockButton == false) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
	        	}

	        	createJoinStallDialog("Please enter a stall name and password to join a new stall.");
        }
    };
    
    private void createJoinStallDialog(String message) {
		dialog = new Dialog(ThoughtsFromThePot.this);

		dialog.setContentView(R.layout.joinstalldialog);
		dialog.getWindow();
		
		android.view.WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        params.height = LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); 
        
		dialog.setTitle("Join Stall");
		
		TextView stallMessage = (TextView) dialog.findViewById(R.id.stallMessage);
		stallMessage.setText(message);

		Button stallSubmitButton = (Button) dialog.findViewById(R.id.joinStallSubmitButton);
		stallSubmitButton.setOnClickListener(joinStallSubmitListener);
		
		Button stallCancelButton = (Button) dialog.findViewById(R.id.joinStallCancelButton);
		stallCancelButton.setOnClickListener(joinStallCancelListener);

		dialog.show();
    }
    
    private void createStallPasswordDialog(String message) {
		dialog = new Dialog(ThoughtsFromThePot.this);

		dialog.setContentView(R.layout.enterpassworddialog);
		dialog.getWindow();
		
		android.view.WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        params.height = LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); 
        
		dialog.setTitle("Enter Stall Password");
		
		TextView stallMessage = (TextView) dialog.findViewById(R.id.stallMessage);
		stallMessage.setText(message);

		Button stallSubmitButton = (Button) dialog.findViewById(R.id.joinStallSubmitButton);
		stallSubmitButton.setOnClickListener(stallPasswordSubmitListener);
		
		Button stallCancelButton = (Button) dialog.findViewById(R.id.joinStallCancelButton);
		stallCancelButton.setOnClickListener(joinStallCancelListener);

		dialog.show();
    }
    
	private OnClickListener createStallSubmitListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}

			EditText nameText = (EditText) dialog.findViewById(R.id.createStallName);
			EditText passText = (EditText) dialog.findViewById(R.id.createStallPassword);
        	
        	String name = nameText.getText().toString();
        	String pass = passText.getText().toString();
        	
        	String testName = name.replaceAll(" ", "");
        	String testPass = pass.replaceAll(" ", "");
        	
        	//TODO: check length and char types submitted
        	
        	if (testName == null || testPass == null || testName.length() == 0 || testPass.length() == 0) {
        		
        	} else {
			
				servletConnector sc = new servletConnector();
	
				try {
					String result = sc.rateThought(thoughtId, 0, currentStallName, currentStallPassword);
					if (result.equals("1")) { //otherwise there was an error!
						
						Toast.makeText(getApplicationContext(), "Stall created successfully.",Toast.LENGTH_SHORT).show();
						
						dialog.dismiss();
					}
					else {
						Toast.makeText(getApplicationContext(), "Unable to create stall. Please try again later.",Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
				}
        	}
		}
	};
	
	private OnClickListener createStallCancelListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}

			dialog.dismiss();
		}
	};
	
	private OnClickListener stallPasswordSubmitListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}
			EditText passText = (EditText) dialog.findViewById(R.id.joinStallPassword);

        	String pass = passText.getText().toString();

        	String testPass = pass.replaceAll(" ", "");
        	
        	//TODO: check length and char types submitted
        	
        	if (testPass == null || testPass.length() == 0) {
        		
        	} else {
			
				servletConnector sc = new servletConnector();
	
				try {
					runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_NEW, currentStallName, pass, "");
	                thread = new Thread(runnable);    
	                thread.start();
	                
	                dialog.dismiss();

//					if (result.equals("1")) { //otherwise there was an error!
//						
//						Toast.makeText(getApplicationContext(), "Stall created successfully.",Toast.LENGTH_SHORT).show();
//						
//						dialog.dismiss();
//					}
//					else {
//						Toast.makeText(getApplicationContext(), "Unable to create stall. Please try again later.",Toast.LENGTH_SHORT).show();
//					}
				} catch (Exception e) {
				}
        	}
		}
	};
	
	private OnClickListener joinStallSubmitListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}

			EditText nameText = (EditText) dialog.findViewById(R.id.joinStallName);
			EditText passText = (EditText) dialog.findViewById(R.id.joinStallPassword);
        	
        	String name = nameText.getText().toString();
        	String pass = passText.getText().toString();
        	
        	String testName = name.replaceAll(" ", "");
        	String testPass = pass.replaceAll(" ", "");
        	
        	//TODO: check length and char types submitted
        	
        	if (testName == null || testPass == null || testName.length() == 0 || testPass.length() == 0) {
        		
        	} else {
			
				servletConnector sc = new servletConnector();
				
				displayThoughtType = REFRESH_TYPE_NEW;
	
				try {
					runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_ERASE, name, pass, "join");
	                thread = new Thread(runnable);    
	                thread.start();
	                
	                dialog.dismiss();

//					if (result.equals("1")) { //otherwise there was an error!
//						
//						Toast.makeText(getApplicationContext(), "Stall created successfully.",Toast.LENGTH_SHORT).show();
//						
//						dialog.dismiss();
//					}
//					else {
//						Toast.makeText(getApplicationContext(), "Unable to create stall. Please try again later.",Toast.LENGTH_SHORT).show();
//					}
				} catch (Exception e) {
				}
        	}
		}
	};
	
	private OnClickListener joinStallCancelListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}

			dialog.dismiss();
		}
	};
	
	private OnItemSelectedListener stallSpinnerListener = new OnItemSelectedListener() {
	    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
		    if (stallSpinnerActivated == false) {
	    		stallSpinnerActivated = true;
		    } else {
		    	if (hapticEnabled) { 
		    		parentView.setHapticFeedbackEnabled(true);
		    		parentView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
				}
		    	
		    	
		    }
	    }

	    public void onNothingSelected(AdapterView<?> parentView) {
	        // your code here
	    }
	};
    
    private OnClickListener writeButtonListener = new OnClickListener() {
        public void onClick(View v) {
        	//if (lockButton == false) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
	        	}
	        	
	        	displayThoughtType = REFRESH_TYPE_POST;
	        	
	        	setButtonBottom(3);
	        	
	        	TextView title = (TextView) findViewById(R.id.pageTitle);
	        	title.setText("post thought");
	        	
	        	removeAllFeedRows();
	        	displayPostPage();
        }
    };
    
    private OnClickListener settingsButtonListener = new OnClickListener() {
        public void onClick(View v) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
		    	}
		    	Intent intent = new Intent(ThoughtsFromThePot.this, Preferences.class);
		    	Bundle bundle = new Bundle();
		    	bundle.putInt("themeNumber", themeNumber);
		    	
		    	intent.putExtras(bundle);
		    	
		    	startActivityForResult(intent,SETTINGS);  
        }
    };
    
    private OnClickListener moreButtonListener = new OnClickListener() {
        public void onClick(View v) {
	        	if (hapticEnabled) {
		        	v.setHapticFeedbackEnabled(true);
		        	v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
	        	}
	        	((Button)v).setText("Querying Server for More Thoughts...");
	        	
	        	runnable = new refreshFeed(displayThoughtType, REFRESH_TYPE_APPEND, currentStallName, currentStallPassword, "");
	            thread = new Thread(runnable);    
	            thread.start();  
        }
    };
    
	private OnClickListener likeImageListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) {
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}

			servletConnector sc = new servletConnector();

			try {
				String result = sc.rateThought(thoughtId, 1, currentStallName, currentStallPassword);
				if (result.equals("1")) { //otherwise there was an error!

					for (int i = 0; i < thoughtList.size(); i++)
					{
						if (thoughtList.get(i).getId() == thoughtId) {
							thoughtList.get(i).setLikes(thoughtList.get(i).getLikes()+1);
							
							if (i != 0) {
								if (thoughtList.get(i).getLikes() > thoughtList.get(i-1).getLikes()) {
									thoughtContainer tempTc = thoughtList.get(i);
									thoughtList.set(i, thoughtList.get(i-1));
									thoughtList.set(i-1, tempTc);
									i = thoughtList.size();
								}
							}
						}
					}
					
					rethemeFeedscreen();
					
					Toast.makeText(getApplicationContext(), "Rating succeeded.",Toast.LENGTH_SHORT).show();
					
					dialog.dismiss();
					rethemeFeedscreen();
					
				}
				else {
					Toast.makeText(getApplicationContext(), "Rating failed.",Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
			} 
		}
	};

	private OnClickListener dislikeImageListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) { 
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}

			servletConnector sc = new servletConnector();

			try {
				String result = sc.rateThought(thoughtId, 0, currentStallName, currentStallPassword);
				if (result.equals("1")) { //otherwise there was an error!
					
					for (int i = 0; i < thoughtList.size(); i++)
					{
						if (thoughtList.get(i).getId() == thoughtId) {
							thoughtList.get(i).setDislikes(thoughtList.get(i).getDislikes()+1);
						}
					}
					
					rethemeFeedscreen();
					
					Toast.makeText(getApplicationContext(), "Rating succeeded.",Toast.LENGTH_SHORT).show();
					
					dialog.dismiss();
					rethemeFeedscreen();
				}
				else {
					Toast.makeText(getApplicationContext(), "Rating failed.",Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
			} 
		}
	};

	private OnClickListener thoughtRowListener = new OnClickListener() {
		public void onClick(View v) {
			if (hapticEnabled) {
				v.setHapticFeedbackEnabled(true);
				v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
			}
			//((TableRow)v).set

			//open a popup box for like vs dislike
			dialog = new Dialog(ThoughtsFromThePot.this);

			dialog.setContentView(R.layout.thoughtratingdialog);
			dialog.getWindow();
			
			android.view.WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); 
            params.width = LayoutParams.FILL_PARENT; 
            params.height = LayoutParams.WRAP_CONTENT;
            dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); 
            
			dialog.setTitle("Rate Thought");

			int id = (int)v.getId();
			thoughtContainer tc = thoughtList.get(id);
    
			TextView user = (TextView) dialog.findViewById(R.id.user);
			user.setText(tc.getUsername());
			user.setTextColor(Color.parseColor(themeLightColor));
			user.setTextSize(13);

			TextView text = (TextView) dialog.findViewById(R.id.text);
			text.setText(tc.getThought());
			text.setTextSize(13);
			//text.setTextColor(Color.parseColor(themeLightColor));

			TextView date = (TextView) dialog.findViewById(R.id.date);
			date.setText(tc.getDate());
			date.setTextSize(11);
			date.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);

			thoughtId = tc.getId();

			Button flushButton = (Button) dialog.findViewById(R.id.flushButton);
			flushButton.setOnClickListener(dislikeImageListener);
			flushButton.setBackgroundColor(Color.parseColor(themeLightColor));
			flushButton.setTextColor(Color.WHITE);
			//flushButton.setTypeface(Typeface.DEFAULT_BOLD);
			
			Button leaveButton = (Button) dialog.findViewById(R.id.leaveButton);
			leaveButton.setOnClickListener(likeImageListener);
			leaveButton.setBackgroundColor(Color.parseColor(themeLightColor));
			leaveButton.setTextColor(Color.WHITE);
			//leaveButton.setTypeface(Typeface.DEFAULT_BOLD);

			dialog.show();
		}
	};

    /**************************************
     *         UTILITY FUNCTIONS
     *************************************/
    
    /* Gets current time */
	public static String getTime() {
	    Calendar cal = Calendar.getInstance();
	    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
	    return sdf.format(cal.getTime());
	}
}